#!/bin/bash

if [ $# != 2 ] ; then 
    echo "USAGE: $0 '192.168.0.2 192.168.0.3 102.168.0.4' password" 
    exit 1; 
fi

# 生成密钥
[ -f ~/.ssh/id_rsa ] || ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

# 安装 expect
echo 'Install expect .... '
[ -f /usr/bin/expect ] || yum -y install expect >/dev/null

# 将本机公钥发送到远程主机
SSH_KEY(){
/usr/bin/expect -c "
set timeout 30
spawn ssh-copy-id -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa.pub root@$1
expect {
    password: {
        send $2\r;
        interact;
    }
}
"
}

for IP in $1; do
    SSH_KEY $IP $2
    ssh $IP "[ -f ~/.ssh/id_rsa ] || ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa"
    pub_key="$(echo `ssh $IP cat ~/.ssh/id_rsa.pub`)\n${pub_key}"
done

flag=$(cat .ssh/authorized_keys | wc -l)
if [ $flag -eq 1 ]; then
    echo -e $pub_key >~/.ssh/authorized_keys
    for IP in $1; do
        scp ~/.ssh/authorized_keys $IP:~/.ssh/authorized_keys
        ssh $IP "echo -e 'Host *\n  UserKnownHostsFile /dev/null\n  StrictHostKeyChecking no\n  LogLevel quiet\n  Port 22' > ~/.ssh/config"
    done
fi

# test
for IP in $1; do
    echo Local: $IP
    # ssh -T -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $IP "for IP in $1;do ssh -T -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \$IP hostname -I; done"
    ssh -T -o StrictHostKeyChecking=no $IP "
        for IP in $1; do 
            ssh -T -o StrictHostKeyChecking=no \$IP echo 0 /dev/null >/dev/null 2>&1
            ssh -T -o StrictHostKeyChecking=no \$IP hostname -I
    done"
done
